package com.aliang.shopping.security.auth;

import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.exception.ServiceException;

import java.util.Objects;

/**
 * 存入登录信息容器
 */
public class UserHolder {
    private static final ThreadLocal<Payload> THREAD_LOCAL = new ThreadLocal<>();

    public static void set(Payload payload) {
        THREAD_LOCAL.set(payload);
    }

    public static Payload get() {
        return THREAD_LOCAL.get();
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }

    public static Long getUserId() {
        Long userId = get().getId();
        if (Objects.isNull(userId)) {
            throw new ServiceException(ResultCodeEnum.USER_NOT_LOGIN);
        }
        return userId;
    }

    public static Integer getUserRole() {
        return get().getRole();
    }
}
